package com.ai.file;


import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileInT {
    public static void main(String[] args) {
        String fileURL = "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Dz0nfvcnz6sFJuIOTJsKgLeS/user-GEgWGmXjIYsk89ssD35AFlN4/img-XyNiiUBGJJZZyYnJXMfI8oSv.png?st=2024-02-25T01%3A43%3A52Z&se=2024-02-25T03%3A43%3A52Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-02-24T23%3A41%3A25Z&ske=2024-02-25T23%3A41%3A25Z&sks=b&skv=2021-08-06&sig=vMOFlXvNsJZfJQYmEJDxv0Miw3UorPq0xWr3O1aMChg%3D";
        // 将这里的字符串替换为你的链接
        String saveDir = "C:\\Users\\14550\\Pictures\\loadCookie.png";
        //"/Users/username/Desktop/myfile.pdf"
        try {
            downloadFile(fileURL, saveDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void downloadFile(String fileURL, String saveDir)
            throws Exception {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();
        // 检查服务器响应
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 打开输入流
            InputStream inputStream = httpConn.getInputStream();
            Path filePath = Paths.get(saveDir);
            Path newPath = Files.createFile(filePath);
            // 打开输出流
            FileOutputStream outputStream = new FileOutputStream(saveDir);
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            // 读取数据
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            // 关闭流 outputStream.close(); inputStream.close();
            System.out.println("文件下载完成，保存在: " + saveDir);
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }
}